var util = require('../../utils/util.js');
var time = util.formatTimes;
var addressName;
var app = getApp();
var uploadURL='https://hd.gzfzkj.com/xbgapi/Report/Sub';
Page({
  data:{
    imageList:['/image/addImage.png'],
    timeNow:'',//报送时间
    titleText:null,
    contentText:null,
    uploadName:'',
    userInfo: {},
    authDeny:0,
    showText: '小程序需要您的微信授权才能使用',
    nameUser:null
  },
  setting: function () {//前往设置
    var that = this
    wx.openSetting({
      success(res) {
        console.log(res)
        var authDeny = that.data.authDeny
        if (res.errMsg == 'openSetting:ok') {
          console.log('1')
          that.setData({
            authDeny: 1
          })
          that.getUsetInfoNew();
        } else {
          console.log('2')
          that.setData({
            authDeny: 2
          })
        }
      }
    })

  },
  selectImageTap:function(){//图片选择
  var that = this
  var imageList = that.data.imageList
  console.log('数组是：'+that.imageList)
if(imageList.length<2){
       wx.chooseImage({
           count: 1, // 默认9
           sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
           sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
           success: function (res) {
    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
           var tempFilePaths = res.tempFilePaths
            for(var i = 0; i < res.tempFilePaths.length; i++){
                imageList.push(res.tempFilePaths[i]);
                that.setData({
                   imageList:imageList 
                 })
            }
          }
       })
      }else{
        wx.showToast({
             title: '只能选择最多1张图片',
             icon: 'success',
             duration: 1500
            })
      }
  },
  delectImage:function(event){//删除图片
         var that = this
         var imageList = that.data.imageList
         imageList.splice(event.currentTarget.dataset.idx,1);
         that.setData({
           imageList:imageList
         })

  },
  showMacImageView:function(event){//点击放大图片
         var that = this
         var showImaggeView = that.data.showImaggeView
         console.log('点击放大图片')
         var imageList = that.data.imageList
         wx.previewImage({
            current: imageList[event.currentTarget.dataset.idx], // 当前显示图片的http链接
            urls: imageList // 需要预览的图片http链接列表
})
  },
  inputTitle:function(e){//输入标题触发的方法
          var that = this
          var titleText = that.data.titleText
          that.setData({
               titleText:e.detail.value
              })
  },
  inputContent:function(e){//输入报告内容
          var that = this
          var contentText = that.data.contentText
          that.setData({
               contentText:e.detail.value
              })
  },
  inputName:function(e){//输入报告人的真是姓名
           var that = this
           var nameUser = that.data.nameUser
           that.setData({
             nameUser: e.detail.value
                }) 
  },
  onLoad:function(options){
    var that = this
    wx.getStorage({
      key: 'openId',
      success: function (res) {
        that.getTimeAndUserInfo();
        var openId = res.data
        console.log('openId' + openId)
        var authDeny = that.data.authDeny
        that.setData({
          authDeny: 1
        });
      },
      fail: function (res) {
        that.getUsetInfoNew();
      }
    })
},
 getTimeAndUserInfo:function(){
   var that = this
  //调用应用实例的方法获取全局数据
  app.getUserInfo(function (userInfo) {
    //更新数据
    that.setData({
      userInfo: userInfo,
      uploadName: userInfo.nickName
    })
  })
  // 生命周期函数--监听页面加载
  var timeNow = that.data.timeNow
  that.setData({//获取当前日期
    timeNow: util.formatDateNow(new Date)
  })
 //调用应用实例的方法获取全局数据
        app.getUserInfo(function (userInfo) {
          //更新数据
          that.setData({
            userInfo: userInfo,
            uploadName: userInfo.nickName
          })
        })
        // 生命周期函数--监听页面加载
        var timeNow = that.data.timeNow
        that.setData({//获取当前日期
          timeNow: util.formatDateNow(new Date)
        })

},
  getUsetInfoNew: function () {
    var that = this
    wx.getUserInfo({
      success: function (res) {
        // 请求==opened
        that.setData({
          userInfo: res.userInfo,
          uploadName: res.userInfo.nickName
        })
        var encryptedData = res.encryptedData
        var iv = res.iv
        console.log('iv:' + iv + ' encryptedData: ' + app.data.sessionIdUser)
        wx.showLoading({
          title: '正在获取用户信息',
          mask: true,
        })
        wx.request({
          url: 'https://hd.gzfzkj.com/xbgapi/Index/DecodeEncryptedData',
          method: 'POST',
          header: { 'Content-Type': 'application/x-www-form-urlencoded' },
          data: {
            dtype: 'USERINFO',
            encryptedData: encryptedData,
            iv: iv,
            sessionId: app.data.sessionIdUser
          },
          success: function (res) {
            var openId = res.data.decodedEntity.openId
            console.log('获取用户openId成功' + openId)
            wx.setStorage({
              key: 'openId',
              data: openId,
              success: function () {
                wx.hideLoading()
                that.setData({
                  authDeny: 1
                });
              },
            })

          },
          fail: function (obj) {

          },
        })
      },
      fail: function (res) {
        if (res.errMsg == "getUserInfo:cancel" || res.errMsg == "getUserInfo:fail auth deny") { //用户未授权
          wx.showModal({
            title: '提示',
            content: '使用小程序需要您进行授权',
            success: function (res) {
              if (res.confirm) {
                that.setting();
              } else if (res.cancel) {
                var authDeny = that.data.authDeny
                that.setData({
                  authDeny: 2
                })
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
    // 请求==opened
  },
saveData:function(){//保存数据
    var that = this
    if (that.data.titleText != null && that.data.contentText != null){
// 获取openid
          wx.getStorage({
              key: 'openId',
               success: function(res) {
              var openId=res.data
              var ListName = ['imagezero','imageone','imagetwo']
// 获取openid
wx.showLoading({
  title: '正在提交……',
})
//提交数据
if(that.data.imageList.length>1){
  var name;
  for(var i = 1;i<that.data.imageList.length;i++){
    if (that.data.nameUser!=null){
      name = that.data.nameUser;
    }else{
      name = that.data.uploadName;
    }
    console.log('提交人的名字是'+name)
     wx.uploadFile({
         url: uploadURL, 
         filePath: that.data.imageList[i],
         name: ListName[i],
         formData:{
           'title': that.data.titleText,
           'content': that.data.contentText,
           'speakeropenid':openId,
           'speakerrealname': that.data.name
          },
         success: function(res){
            var imageList = that.data.imageList
            var titleText = that.data.titleText
            var contentText = that.data.contentText
            that.setData({
                imageList:['/image/addImage.png'],
                titleText:null,
                contentText:null, 
            })
            wx.setStorage({
              key: "myAddList",
              data: true,
              success: function (res) {
                console.log('刷新')
              },
              fail: function () {
                console.log('存到本地的刷新状态失败')
              }
            })
            wx.hideLoading()
            wx.showToast({
             title: '提交成功',
             icon: 'success',
             duration: 1500
            })
      },
      fail:function(res){
        wx.hideLoading()
             wx.showToast({
             title: res.data.msg,
             icon: 'fail',
             duration: 1500
            })
      }
    })
  }
}else{
  var name;
  if (that.data.nameUser != null) {
    name = that.data.nameUser;
  } else {
    name = that.data.uploadName;
  }
  console.log('提交人的名字是1' + name)
      wx.request({
          url: uploadURL,
          data: {
           'title': that.data.titleText,
           'content': that.data.contentText,
           'speakeropenid':openId,
           'speakerrealname':name
          }, 
          method: "POST",
          header: { 'Content-Type': 'application/x-www-form-urlencoded'},
          success: function (res) {
            var imageList = that.data.imageList
            var titleText = that.data.titleText
            var contentText = that.data.contentText
            var nameUser = that.data.nameUser
            that.setData({
                imageList:['/image/addImage.png'],
                titleText:null,
                contentText:null, 
            })
            wx.hideLoading()
            wx.showToast({
             title: '提交成功',
             icon: 'success',
             duration: 1500
            })
      },
      fail:function(res){
         wx.hideLoading()
             wx.showToast({
             title: res.data.msg,
             icon: 'fail',
             duration: 1500
            })
      }
    }) 

}

  }
 })
    }else{
      if (that.data.titleText == null || that.data.titleText.length==0 ){
        wx.showToast({
          title: '标题不可为空',
          icon: 'success',
          duration: 1500
        })
        return;
      }
      if (that.data.contentText == null || that.data.contentText.length == 0) {
        wx.showToast({
          title: '报告内容不可为空',
          icon: 'success',
          duration: 1500
        })
        return;
      }
    }
},
  onReady:function(){
    // 生命周期函数--监听页面初次渲染完成

  },
  onShow:function(){
    // 生命周期函数--监听页面显示
    var that = this
    console.log('-------')
    wx.getStorage({
      key: 'openId',
      success: function (res) {
        var openId = res.data
        if (res.data) {
          var authDeny = that.data.authDeny
          if (authDeny != 1) {
            that.getTimeAndUserInfo();
            that.setData({
              authDeny: 1
            });
          }
        }
      }
    })
  },
  onHide:function(){
    // 生命周期函数--监听页面隐藏
    
  },
  onUnload:function(){
    // 生命周期函数--监听页面卸载
    
  },
  onPullDownRefresh: function() {
    // 页面相关事件处理函数--监听用户下拉动作
    
  },
  onReachBottom: function() {
    // 页面上拉触底事件的处理函数
    
  },
  onShareAppMessage: function() {
    // 用户点击右上角分享
    return {
      title: 'title', // 分享标题
      desc: 'desc', // 分享描述
      path: 'path' // 分享路径
    }
  }
})